import { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addProduct, removeProduct } from '../store/productsSlice';

function Products() {
  const dispatch = useDispatch();
  const products = useSelector((state) => state.products.items);
  const [productName, setProductName] = useState('');
  const [productPrice, setProductPrice] = useState('');
  const [selectedProducts, setSelectedProducts] = useState([]);

  const handleAddProduct = () => {
    if (!productName || !productPrice) {
      alert('请输入产品名称和价格！');
      return;
    }

    const newProduct = {
      id: Date.now(),
      name: productName,
      price: Number(productPrice),
    };

    dispatch(addProduct(newProduct));
    setProductName('');
    setProductPrice('');
  };

  // 处理单个产品选择
  const handleSelectProduct = (productId) => {
    setSelectedProducts((prev) => {
      if (prev.includes(productId)) {
        return prev.filter((id) => id !== productId);
      } else {
        return [...prev, productId];
      }
    });
  };

  // 处理全选
  const handleSelectAll = () => {
    if (selectedProducts.length === products.length) {
      setSelectedProducts([]);
    } else {
      setSelectedProducts(products.map((product) => product.id));
    }
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedProducts.length === 0) {
      alert('请先选择要删除的产品！');
      return;
    }

    if (window.confirm(`确定要删除选中的 ${selectedProducts.length} 个产品吗？`)) {
      selectedProducts.forEach((productId) => {
        dispatch(removeProduct(productId));
      });
      setSelectedProducts([]);
    }
  };

  return (
    <div className="container">
      <div className="products-header">
        <h1>产品管理</h1>
        <div className="product-form">
          <div className="input-group">
            <input
              type="text"
              value={productName}
              onChange={(e) => setProductName(e.target.value)}
              placeholder="请输入产品名称"
              className="custom-input"
            />
            <input
              type="number"
              value={productPrice}
              onChange={(e) => setProductPrice(e.target.value)}
              placeholder="请输入产品价格"
              className="custom-input"
            />
            <button onClick={handleAddProduct} className="add-btn">
              添加产品
            </button>
          </div>
        </div>
      </div>

      <div className="products-actions">
        <label className="select-all">
          <input
            type="checkbox"
            checked={selectedProducts.length === products.length && products.length > 0}
            onChange={handleSelectAll}
          />
          全选
        </label>
        {selectedProducts.length > 0 && (
          <button onClick={handleBatchDelete} className="batch-delete-btn">
            批量删除 ({selectedProducts.length})
          </button>
        )}
      </div>

      <div className="products-grid">
        {products.map((product) => (
          <div
            key={product.id}
            className={`product-card ${selectedProducts.includes(product.id) ? 'selected' : ''}`}
          >
            <div className="product-card-header">
              <input
                type="checkbox"
                checked={selectedProducts.includes(product.id)}
                onChange={() => handleSelectProduct(product.id)}
                className="product-checkbox"
              />
            </div>
            <div className="product-info">
              <h3>{product.name}</h3>
              <p className="price">¥{product.price}</p>
            </div>
            <button onClick={() => dispatch(removeProduct(product.id))} className="delete-btn">
              删除
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

export default Products;
